package com.musiklegal;



import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class LoginWeb extends Activity
{
	static Activity p;
	WebView browser;
	static String urlTo;
	
	static boolean fromSettings = false;
	InformationParser mparse;
	Handler h = new Handler();
	
	public void onCreate(Bundle saved)
	{
		if(!MusikLegal.internet(getApplicationContext()))
			finish();
		super.onCreate(saved);
		
		setContentView(R.layout.loginweb);
		browser = (WebView) findViewById(R.id.webView1);
		CookieSyncManager csm = CookieSyncManager.createInstance(getApplicationContext());
		csm.startSync();
		CookieManager cm = CookieManager.getInstance();
		cm.removeAllCookie();
		browseTo(browser, urlTo);
		
		
		
	}

	private void browseTo(WebView wv, String url) 
	{
		wv.getSettings().setJavaScriptEnabled(true);
		wv.getSettings().setPluginsEnabled(true);
		wv.getSettings().setAppCacheEnabled(false);
		wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		wv.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
            	
            	LoginWeb.this.setTitle("Loading...");
                LoginWeb.this.setProgress(progress);
            }
        });
 
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                // Handle the error
            }
 
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
            	
            	
            	view.loadUrl(url);
            	
                return true;
            }
            
            public void onPageFinished(WebView view, String url)
            {
            	LoginWeb.this.setTitle("MUSIKLEGAL");
            	
            	if(check(url))
            	{
            		
            		Log.d("tes","MASUK");
            		view.loadData("<html><p>Processing . . .</p>", "text/html", null);
            		try {
            		DefaultHttpClient mlist = new DefaultHttpClient(); 
        			HttpGet get = new HttpGet(url);
        			
        			HttpResponse mresp = mlist.execute(get);

        			HttpEntity merclist = mresp.getEntity();
        			SAXParserFactory spf = SAXParserFactory.newInstance();
        			SAXParser sp = spf.newSAXParser();
        			XMLReader xr = sp.getXMLReader();
        			
        			mparse = new InformationParser();
        			xr.setContentHandler(mparse);
        			
						xr.parse(retrieveInputStream(merclist));
						new Thread(new Runnable(){

							public void run() {
								
								login(mparse.data.getUse(),mparse.data.getPas());
							}}).start();
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SAXException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (ParserConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
            	}
            
            }
        });
 
		 wv.loadUrl(url);
		
	}
	
	void login(String username,String password)
	{
		
		SharedPreferences mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
		MainMenu.username=username;
		String uid = MusikLegal.getUID(getApplicationContext());
        
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost login = new HttpPost("http://secure.musiklegal.com/user/validate");
        HttpPost contact = new HttpPost("http://secure.musiklegal.com/app_contact/contact");
        HttpPost subs = new HttpPost("http://secure.musiklegal.com/subscription/check");
        HttpPost bal = new HttpPost("http://secure.musiklegal.com/user/user_info");
        
        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
        List< BasicNameValuePair > nvcs = new ArrayList< BasicNameValuePair >();
        List< BasicNameValuePair > nvss = new ArrayList< BasicNameValuePair >();
        List< BasicNameValuePair > nvbs = new ArrayList< BasicNameValuePair >();
        
        nvps.add(new BasicNameValuePair("USERNAME", username));
        nvps.add(new BasicNameValuePair("PASSWORD", password));
        nvcs.add(new BasicNameValuePair("USERNAME", username));
        nvcs.add(new BasicNameValuePair("UID", uid));
        nvss.add(new BasicNameValuePair("USERNAME", username));
        nvss.add(new BasicNameValuePair("UID", uid));
        nvbs.add(new BasicNameValuePair("USERNAME", username));;
        nvbs.add(new BasicNameValuePair("PASSWORD", password));

        try {

        	  UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
        	  UrlEncodedFormEntity c_entity = new UrlEncodedFormEntity(nvcs,HTTP.UTF_8);
        	  UrlEncodedFormEntity s_entity = new UrlEncodedFormEntity(nvss,HTTP.UTF_8);
        	  UrlEncodedFormEntity b_entity = new UrlEncodedFormEntity(nvbs,HTTP.UTF_8);
        	  
        	  login.setEntity(p_entity);
        	  contact.setEntity(c_entity);
        	  subs.setEntity(s_entity);
        	  bal.setEntity(b_entity);
        	  
              HttpResponse response = client.execute(login);
              client = new DefaultHttpClient();
              HttpResponse response2 = client.execute(contact);
              client = new DefaultHttpClient();
              HttpResponse response3 = client.execute(subs);
              client = new DefaultHttpClient();
              HttpResponse response4 = client.execute(bal);
              
              HttpEntity responseEntity = response.getEntity();
              HttpEntity responseEntity2 = response2.getEntity();
              HttpEntity responseEntity3 = response3.getEntity();
              HttpEntity responseEntity4 = response4.getEntity();
              
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();
              XMLReader xr = sp.getXMLReader();
              
              SAXParserFactory cpf = SAXParserFactory.newInstance();
              SAXParser cp = cpf.newSAXParser();
              XMLReader cr = cp.getXMLReader();
              
              SAXParserFactory bpf = SAXParserFactory.newInstance();
              SAXParser bp = bpf.newSAXParser();
              XMLReader br = bp.getXMLReader();
              
              SAXParserFactory lpf = SAXParserFactory.newInstance();
              SAXParser lp = lpf.newSAXParser();
              XMLReader lr = lp.getXMLReader();
              
              LoginHandler loginHand = new LoginHandler();
              LoginHandler contHand = new LoginHandler();
              LoginHandler subsHand = new LoginHandler();
              LoginHandler balHand = new LoginHandler();
              
              xr.setContentHandler(loginHand);
              cr.setContentHandler(contHand);
              br.setContentHandler(subsHand);
              lr.setContentHandler(balHand);
              
              xr.parse(retrieveInputStream(responseEntity));
              cr.parse(retrieveInputStream(responseEntity2));
              br.parse(retrieveInputStream(responseEntity3));
              lr.parse(retrieveInputStream(responseEntity4));
              
              ParsedLoginDataSet loginset = loginHand.getParsedLoginData();
              ParsedLoginDataSet contactset = contHand.getParsedLoginData();
              ParsedLoginDataSet subset = subsHand.getParsedLoginData();
              ParsedLoginDataSet balset = balHand.getParsedLoginData();
              
              
              //Toast.makeText(getApplicationContext(), loginset.getExtractedString(), Toast.LENGTH_SHORT).show();

              if (loginset.getExtractedString().equals("SUCCESS")&&contactset.getExtractedString().equals("SUCCESS")) 
              {
            	  h.post(new Runnable(){

					public void run() {
						// TODO Auto-generated method stub
						 showDialog(0);
					}});
            	   
                    SharedPreferences.Editor editor=mPreferences.edit();
                    editor.putString("UserName", username);
                    editor.putString("PassWord", password);
                    editor.putString("Balance", balset.getBal());
                    editor.putString("picture", balset.getProfPict());
                    if(balset.getFB()!=null)
                    {
                    	if(balset.getFB().equals("0"))
                    	{
                    	editor.putString("FBId", username);
                    	}
                    	editor.putString("FBId", balset.getFB());
                    }
                    if(balset.getTW()!=null)
                    {
                    	if(balset.getTW().equals("0"))
                    	{
                    	editor.putString("TWId", username);
                    	}
                    	editor.putString("TWId", balset.getTW());
                    }
	
                    if(subset.getSiD()!=null)
                    {
                    	editor.putString("SubId", subset.getSiD());
                    }
                    if(subset.getDate()!=null)
                    {
                    	editor.putString("SubDate", subset.getDate());
                    }
                    
                    editor.commit();         
//                    Toast.makeText(getApplicationContext(), MusikLegal.mPreferences.getString("SubId", null),
//                           Toast.LENGTH_SHORT).show();
                    if(!fromSettings)
                    	p.finish();
                    	finish();
                    if(!fromSettings)
                    {
                    	h.post(new Runnable(){

							public void run() {
								// TODO Auto-generated method stub
								startActivity(new Intent(getApplicationContext(), MainMenu.class));
							}});
                    	
                    }
                    fromSettings =false;
                    
                    
              }
        } catch (Exception e)
        {
        	
        }
		
	}

	private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
        }
	
	public boolean check(String url)
	{
		URL ur;
		try {
			ur = new URL(url);
			ur.openConnection();
			InputStream is = (ur.openStream());
			byte[] b  = new byte[7];
			is.read(b);
			String k=new String(b).trim();
			Log.d("html", k);
			if(k!=null&&!k.equals(""))
			{
				
				return	k.startsWith("<reply>");
			}
			else 
				return false;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
}
